package com.ys.controller.api.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.ys.entity.business.TpAplusFile;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.TpAplusFileService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * A+管理
 */
@Controller
@RequestMapping("/api/inter/tpAplusFile")
public class ApiInterTpAplusFileController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTpAplusFileController.class);
    private static Long MENU_ID = 10177L;


    @Autowired
    private CommonApiService<TpAplusFile> commonApiService;
    @Autowired
    private TpAplusFileService tpAplusFileService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TpAplusFile setSeachSql(TpAplusFile cond){
        cond.addField("B.Code AS code");
        cond.addField("B.Name AS name");
        cond.addField("B.CodeMerge AS codeMerge");
        //cond.addField("B.CodeMerge AS codeMerge");
        cond.addField("O.VGsJc AS vgsJc");
        //cond.addField("S.Platform AS platform");
        //cond.addField("S.RegionName AS regionName");
        //cond.addField("S.CountryName AS countryName");

        cond.addField("O.CUser AS cUser");
        cond.addLeftJoin("TP_Boutique B ON A.BoutiqueId = B.Id");
        cond.addLeftJoin("TP_BoutiqueSiteDetail SD ON A.BoutiqueSiteDetailId = SD.Id");
        cond.addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = A.VgsBm");
        /*
        cond.addLeftJoin("TP_AmazonRegionItem I ON S.AmazonRegionItemId = I.Id");
        cond.addLeftJoin("TP_AmazonRegion R ON I.RegionCode = R.Code");
        cond.addField("I.CountryName AS countryName");//站点
        cond.addField("R.Name AS regionName");//区域
        cond.addField("R.Platform AS platform");//平台
         */

        cond.addLeftJoin("TB_Site S ON S.Id = S.SiteId")
                .addLeftJoin("TP_AmazonRegion B ON B.Code = S.RegionCode")
                .addField("B.Name regionName")
                .addLeftJoin("TB_Platform B1 ON B1.Code = B.PlatformCode")
                .addField("B1.Name platform")
                .addLeftJoin("TB_Country C ON C.Id = S.CountryId")
                .addField("C.Name countryName");

        /*
        cond.addField("I.CountryName AS countryName")//站点
                .addField("R.Name AS regionName")//区域
                .addField("R.Platform AS platform")//平台
         */


        //排序
        cond.setOrderby("A.UpdateTime DESC");
        cond = commonApiService.dataAuth(MENU_ID, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TpAplusFile cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询A+管理表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 查询A+信息，根据精品库站点信息表Id
     */
    @RequestMapping("/searchByBoutiqueSiteDetailId")
    @ResponseBody
    public LayuiTableVoJA searchByBoutiqueSiteDetailId(Model model, HttpServletRequest request, HttpServletResponse response,
                                                       String id
    ){
        try {
            List<Map<String,Object>> resList =  new TpAplusFile()
                    .addField("O.VGsJc AS vgsJc")
                    .addField("O.CUser AS cUser")
                    .addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = A.VgsBm")
                    .setBoutiqueSiteDetailId(Long.parseLong(id))
                    .queryMap();
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
            tableVoJA.setData(jsonArray);
            tableVoJA.setMsg("成功");
            tableVoJA.setCode(0);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 查询A+信息，根据精品库站点信息表Id，详情
     */
    @RequestMapping("/searchByBoutiqueSiteDetailIdByAuth")
    @ResponseBody
    public LayuiTableVoJA searchByBoutiqueSiteDetailIdByAuth(Model model, HttpServletRequest request, HttpServletResponse response,
                                                       String id
    ){
        try {
            TpAplusFile cond = new TpAplusFile();
            cond.addField("O.VGsJc AS vgsJc")
                    .addField("O.CUser AS cUser")
                    .addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = A.VgsBm")
                    .setBoutiqueSiteDetailId(Long.parseLong(id));
            cond = commonApiService.dataAuth(MENU_ID, cond);//权限
            List<Map<String,Object>> resList =  cond
                    .queryMap();
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
            tableVoJA.setData(jsonArray);
            tableVoJA.setMsg("成功");
            tableVoJA.setCode(0);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }




    /**
     * 批量新增、修改
     */
    @RequestMapping("/toAddOrUpdateByList")
    @ResponseBody
    public R toAddOrUpdateByList(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            logger.info("A+批量新增、修改传参："+params);
            String errorMsg = checkParams(params);
            if(errorMsg!=null && !"".equals(errorMsg)){
                return R.error(errorMsg);
            }
            return tpAplusFileService.addOrUpdateByList(params);
        } catch (Exception e) {
            logger.error("新增A+管理表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(Long id){
        try {
            //查询条件
            //Long id = Long.parseLong(ConditionUtil.getConditionValue(conditions, "id"));//精品库站点信息表Id
            String whereString = "A.BoutiqueSiteDetailId = " + id;

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .where("A.MenuId = "+MENU_ID)
                    .setOrderby("A.SortNo ASC")
                    .queryList();

            TpAplusFile cond = new TpAplusFile()
                    .addField("B.Code AS code")
                    .addField("B.Name AS name")
                    .addField("B.CodeMerge AS codeMerge")
                    .addField("B.CodeMerge AS codeMerge")
                    .addField("O.VGsJc AS vgsJc")
                    //.addField("S.Platform AS platform")
                   // .addField("S.RegionName AS regionName")
                    //.addField("S.CountryName AS countryName")
                    .addLeftJoin("TP_Boutique B ON A.BoutiqueId = B.Id")
                    .addLeftJoin("TP_BoutiqueSiteDetail S ON A.BoutiqueSiteDetailId = S.Id")
                    .addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = A.VgsBm")

                    .addLeftJoin("TB_Site S ON S.Id = S.SiteId")
                    .addLeftJoin("TP_AmazonRegion B ON B.Code = S.RegionCode")
                    .addField("B.Name regionName")
                    .addLeftJoin("TB_Platform B1 ON B1.Code = B.PlatformCode")
                    .addField("B1.Name platform")
                    .addLeftJoin("TB_Country C ON C.Id = S.CountryId")
                    .addField("C.Name countryName")

                    .where(whereString)
                    .setOrderby("A.Code ASC");

            //权限
            //cond = commonApiService.dataAuth(MENU_ID, cond);

            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TpAplusFile> util = new ExportExcelUtils<>(new TpAplusFile());
            String toFilePath = util.exportExcel(listData, listField, "精品库站点详情A+信息表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出精品详情A+信息表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 参数验证
     */
    public String checkParams(Map<String, Object> params){
        Predicate<String> isNotNull = item-> item!=null && !"".equals(item.trim());//是否为空，返回：非空true，空false
        String backMsg = "";
        if(params==null){
            return "参数为空！";
        }
        if(!isNotNull.test(params.get("boutiqueId")+"")){
            return "精品库Id为空！";
        }
        if(!isNotNull.test(params.get("code")+"")){
            return "商品编码为空！";
        }
        if(!isNotNull.test(params.get("boutiqueSiteDetailId")+"")){
            return "精品库站点信息表Id为空！";
        }
        if(!isNotNull.test(params.get("dataList")+"")){
            return "列表参数信息为空！";
        }
        JSONArray dataList = JSONArray.parseArray(params.get("dataList").toString());
        if(dataList.size()>0) {
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject jsonObj = dataList.getJSONObject(i);
                if(!isNotNull.test(jsonObj.get("vgsBm")+"")){
                    backMsg = "第"+(i+1)+"行信息，公司编码为空！";
                }
                if(!isNotNull.test(jsonObj.get("fileName")+"")){
                    backMsg = "第"+(i+1)+"行信息，文件名称为空！";
                }
                if(!isNotNull.test(jsonObj.get("filePath")+"")){
                    backMsg = "第"+(i+1)+"行信息，文件上传有误！";
                }
                if(!isNotNull.test(jsonObj.get("fileType")+"")){
                    backMsg = "第"+(i+1)+"行信息，文件类型为空！";
                }
                if(!isNotNull.test(jsonObj.get("fileSize")+"")){
                    backMsg = "第"+(i+1)+"行信息，文件大小为空！";
                }
                if(!isNotNull.test(jsonObj.get("fileSizeUnit")+"")){
                    backMsg = "第"+(i+1)+"行信息，单位为空！";
                }
            }
        }
        return backMsg;
    }


    /**
     * 删除
     */
    @RequestMapping("/del")
    @ResponseBody
    public R del(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            for(int i=0;i<idList.size();i++) {
                //删除
                tpAplusFileService.del(Long.parseLong(idList.get(0)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除A+出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


}